﻿using System;
using Framework.Common;
using Framework.Resource;
using UnityEngine;
namespace BridgeShips {
    public class LoadAssetHelper : MonoBehaviour, ILoadAssetHelper {
        private event FrameworkAction<object> m_LoadCompleteEvent = null;
        private event FrameworkAction<string> m_LoadErrorEvent = null;
        private event FrameworkAction<int> m_LoadProgressEvent = null;
        private string m_PackageName = null;
        private AssetBundleCreateRequest m_Request = null;
        private bool m_IsLoading = false;

        public event FrameworkAction<object> LoadCompleteEvent {
            add {
                m_LoadCompleteEvent += value;
            }
            remove {
                m_LoadCompleteEvent -= value;
            }
        }
        public event FrameworkAction<string> LoadErrorEvent {
            add {
                m_LoadErrorEvent += value;
            }
            remove {
                m_LoadErrorEvent -= value;
            }
        }
        public event FrameworkAction<int> LoadProgressEvent {
            add {
                m_LoadProgressEvent += value;
            }
            remove {
                m_LoadProgressEvent -= value;
            }
        }

        public void Init() {
            m_PackageName = null;
            m_Request = null;
            m_IsLoading = false;
        }
        public void LoadAssetAsync( string packageName ) {
            m_PackageName = packageName;
            m_Request = AssetBundle.LoadFromFileAsync( string.Format( "{0}/{1}", AssetPath.AssetBundlePath, packageName ) );
            if (m_Request == null) {
                if (m_LoadErrorEvent != null) {
                    m_LoadErrorEvent( "load failed!" );
                }
                return;
            }
            m_IsLoading = true;
        }
        public void Reset() {
            m_PackageName = null;
            m_Request = null;
            m_IsLoading = false;
        }
        public void Destroy() {
            m_LoadCompleteEvent = null;
            m_LoadErrorEvent = null;
            m_LoadProgressEvent = null;
            m_PackageName = null;
            m_Request = null;
        }
        private void Update() {
            if (m_IsLoading == false) return;
            if (m_Request.isDone == true) {
                if (m_LoadCompleteEvent != null)
                    m_LoadCompleteEvent( m_Request.assetBundle );
            }
            else {
                if (m_LoadProgressEvent != null)
                    m_LoadProgressEvent( (int)(m_Request.progress * 100) );
            }
        }
    }
}